package xuegao.study.mall.rbac.service.impl;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xuegao.study.mall.common.model.ums.UmsMenu;
import xuegao.study.mall.common.vo.ums.UmsMenuVo;
import xuegao.study.mall.rbac.service.UmsMenuService;
import xuegao.study.mall.rbac.util.MenuTreeUtils;
import xuegao.study.mall.repo.dao.ums.UmsMenuDao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UmsMenuServiceImpl implements UmsMenuService {
    @Autowired
    private UmsMenuDao umsMenuDao;

    @Override
    public List<UmsMenu> selectList(Long parentId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> params = new HashMap<>();
        params.put("parentId", parentId);
        return umsMenuDao.selectList(params);
    }

    @Override
    public List<UmsMenu> getMenuListByAdminId(Long adminId) {
        return umsMenuDao.getMenuListByAdminId(adminId);
    }

    @Override
    public List<UmsMenuVo> treeList() {
        List<UmsMenu> allMenus = umsMenuDao.selectList(new HashMap<>());
        List<UmsMenuVo> voList = MenuTreeUtils.menusVoTree(allMenus);
        return voList;
    }

    @Override
    @Transactional
    public int addMenu(UmsMenu menu) {
        Long parentId = menu.getParentId();
        if (parentId == 0) {
            menu.setLevel(0);
        } else {
            menu.setLevel(1);
        }
        menu.setCreateTime(new Date());
        return umsMenuDao.insertMenu(menu);
    }

    @Override
    @Transactional
    public int updateMenu(Long id, UmsMenu menu) {
        menu.setId(id);
        return umsMenuDao.updateMenu(menu);
    }

    @Override
    @Transactional
    public int deleteMenuById(Long id) {
        return umsMenuDao.deleteMenuById(id);
    }

    @Override
    public UmsMenu getUmsMenuById(Long id) {
        return umsMenuDao.getById(id);
    }
}
